package cn.tedu.csmall.product.config;

import cn.tedu.csmall.product.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Security配置类
 * @author 何惠民
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    public SecurityConfiguration() {
        log.debug("创建配置类对象：SecurityConfiguration");
    }

    /**
     * Jwt过滤器
     */
    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //请求访问认证授权设置
        //如果同意路径对应多项配置规则,以第一次配置文本

        //路径白名单
        String [] urls = {
                "/favicon.ico",
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
        };


        //启用corsFilter(Spring Security 内置的过滤器,默认不启用  )
        //复杂请求跨域预检问题
        http.cors();

        // 禁用防止伪造跨域攻击的机制禁用
        http.csrf().disable();


        // /*  代表一层 如/a /b    /**代表多层 可以是/a /a/a
        http.authorizeRequests()        //管理请求授权
                //匹配某些请求
//                .mvcMatchers(HttpMethod.OPTIONS,"/**")
//                .permitAll()

                //匹配某些路径
                .mvcMatchers(urls)
                .permitAll()   //直接许可,即不需要通过认证即可访问
                .anyRequest()  //除了以上配置过的其他所有请求
                //要求是"已经通过认证的"
                .authenticated();

        //将JWT过滤器添加到Spring Security框架的过滤链中
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);

        //启用登录表单
        //当未认证时,
        //如果启用了表单,会自动重定向到登录表单,
        // 如果没有启用则会显示403错误
//        http.formLogin();
    }
}
